(function () {
  function AddCopyBtnSyle() {
    let copyBtnStyle = document.createElement('style');
    copyBtnStyle.type = 'text/css';

    copyBtnStyle.innerHTML = `  #copyScriptCodeOk {
    padding: 20px;
    border: 2px solid #3b7d00;
    text-align: center;
    text-transform: uppercase;
    position: relative;
    overflow: hidden;
    transition: 0.3s;
  }
  
  #copyScriptCodeOk:after {
    position: absolute;
    transition: 0.3s;
    content: "";
    width: 0;
    left: 50%;
    bottom: 0;
    height: 3px;
    background: #3b7d00;
  }
  
  
  #copyScriptCodeOk:after {
    height: 120%;
    left: -10%;
    transform: skewX(15deg);
    z-index: -1;
  }
  
  #copyScriptCodeOk:hover {
    cursor: pointer;
  }
  
  #copyScriptCodeOk:hover:after {
    width: 100%;
    left: 0;
  }
  
  
  #copyScriptCodeOk:hover {
    border-radius: 30px;
  }
  
  #copyScriptCodeOk:hover:after {
    width: 0%;
  }`;

    document.body.appendChild(copyBtnStyle);
  }

  document.querySelectorAll('pre').forEach(function (i) {
    i.appendChild(CreateCopyNode());
  });

  /** 产出按钮事件 */
  function CreateCopyNode() {
    let elem = document.createElement('div');
    let content = document.createTextNode('复制代码块');
    elem.appendChild(content);
    let elemStyle = {
      color: '#3b7d00',
      textAlign: 'center',
    };
    Object.keys(elemStyle).forEach((i) => (elem.style[i] = elemStyle[i]));
    elem.setAttribute('id', 'copyScriptCodeOk');
    elem.addEventListener('click', function () {
      let content = this?.parentNode?.querySelector('code')?.innerText;
      copy(content);
      elem.innerText = '复制成功';
    });

    return elem;
  }

  /** 复制到剪切板事件 */
  function copy(text) {
    let textarea = document.createElement('textarea');
    document.body.appendChild(textarea);
    textarea.value = text;
    textarea.select();
    if (document.execCommand('copy')) {
      document.execCommand('copy');
    }
    document.body.removeChild(textarea);
    return textarea;
  }

  AddCopyBtnSyle();
})();
